package model;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;

public class MeanVarianceCalculator {

	public static BigDecimal calculateMean(ArrayList<FrequencyPair> distribution){
		
		if(distribution.size() == 0)
			return BigDecimal.ZERO;
		
		BigDecimal avg = BigDecimal.ZERO;
		BigDecimal val = BigDecimal.ZERO;
		
		for(FrequencyPair fp: distribution){
			val = val.add(fp.getFrequency());
			avg =  avg.add(fp.getFrequency().multiply(new BigDecimal(fp.getNumAsDouble())));
		}
		
		return avg.divide(val, MathContext.DECIMAL128);
	}
	
	public static BigDecimal calculateVariance(ArrayList<FrequencyPair> distribution, boolean isPopulation){
		
		if(distribution.size() == 0)
			return BigDecimal.ZERO;
		
		BigDecimal mean = calculateMean(distribution);
		BigDecimal variance = BigDecimal.ZERO;
		BigDecimal count = BigDecimal.ZERO;
		
		for(FrequencyPair fp: distribution){
			count = count.add(fp.getFrequency());
			BigDecimal currNum = new BigDecimal(fp.getNum());
			currNum = currNum.subtract(mean);
			currNum = currNum.pow(2);
			currNum = currNum.multiply(fp.getFrequency());
			variance = variance.add(currNum);
		}
	
		if(isPopulation)
			return variance.divide(count, MathContext.DECIMAL128);
		
		return variance.divide(count.subtract(BigDecimal.ONE), MathContext.DECIMAL128);
	}
	
}
